import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

axios.defaults.withCredentials = true
// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      config.headers['X-Api-Token'] = store.getters.token
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { status, data } = response
    if (status !== 200) {
      // 状态不正确，服务错误
      return Promise.reject('server error')
    }
    if (!data || data.code !== 200) {
      // data 不存在或者格式不对，接口错误
      return Promise.reject(data.msg ? data.msg : 'api error')
    }
    return Promise.resolve(data.data)
  }, error => {
    console.error(error)
    const { response } = error
    let msg = '请求失败，服务繁忙中……'
    if (response.data && typeof response.data.msg !== 'undefined') {
      msg = response.data.msg

      if (response.data.error_code === 10001) {
        store.dispatch('fedlogOut').then(() => {
          location.reload()// In order to re-instantiate the vue-router object to avoid bugs
        })
      }
    }
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(msg)
  })

const success = data => {
  return {
    res: data,
    err: null
  }
}

const fail = err => {
  return {
    res: null,
    err
  }
}

/**
* 使用es6中的类，进行简单封装
*/
export default class Request {
  // 使用async ... await
  static async get(url, params) {
    try {
      const res = await service.get(url, { params })
      return success(res)
    } catch (err) {
      return fail(err)
    }
  }

  static async post(url, params) {
    try {
      const res = await service.post(url, params)
      return success(res)
    } catch (err) {
      return fail(err)
    }
  }

  static async put(url, params) {
    try {
      const res = await service.put(url, params)
      return success(res)
    } catch (err) {
      return fail(err)
    }
  }

  static async delete(url, params) {
    try {
      const res = await service.delete(url, { data: params })
      return success(res)
    } catch (err) {
      return fail(err)
    }
  }
}
